import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

/*
 * This class is responsible for handling all the jobs present in the major job queue
 * , and based on the information present in the SPS object and the type of task and
 * the no of tasks to be scheduled, assigns each task to a particular server/ cluster
 * in order to manage power usage by :
 * 			1. Load balancing
 * 			2. Deciding on type of task
 * 			3. Present power consumption of server/clusters
 * 			4. (Possibly) past behaviour & history of the server/cluster
 */

public class JobHandler implements IJobHandler,Runnable
{
	protected volatile Boolean running = null;
	private boolean isNewJob;
	
	private Queue<IJob> jobQueue = null;
	private volatile SystemPowerState sps = null;
	private Map<Integer,Integer> jobSchedule = null;
	protected volatile IPowerUsageData pud = null;
	
	public JobHandler(SystemPowerState sps, Boolean running,IPowerUsageData pud)
	{
		this.sps = sps;
		this.running = running;
		this.pud = pud;
		
		jobSchedule = new HashMap<Integer,Integer>();
		jobQueue = new LinkedList<IJob>();
		isNewJob = false;
	}
	
	public void run()
	{
		while(running)
		{
			if(isNewJob)
			{
				// schedule jobs in the job queue
				
				scheduleJobs();
				
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					System.out.println("Exception in job handler thread sleeping");
					e.printStackTrace();
				}
			}
		}
	}
	
	private void scheduleJobs()
	{
		// schedule jobs into different resources based on job types and current power usage
		// for each resource (server/cluster)
		// the scheduled jobs would be stored into the hashmap with the key as the job id and
		// the value as the resource id.
		
		assignJobs();
	}
	
	public void jobIn(IJob newJob)
	{
		jobQueue.offer(newJob);
		isNewJob = true;
	}
	
	private void assignJobs()
	{
		// assign jobs to their respective resources, as given in the job schedule map
	}
}
